<template>
  <div ref="codemirror" class="codemirror" style="height: 100%; font-size: 18px"></div>
</template>
<script>
import { EditorView } from '@codemirror/view'
import { EditorState } from '@codemirror/state'
import { basicSetup } from 'codemirror'
import { ref, watch } from 'vue'
import { MySQL, sql } from '@codemirror/lang-sql'
export default {
  name: 'SqlEditor',
  props: {
    doc: {
      required: false
    },
    focusInit: {
      required: false
    }
  },
  expose: ['setDoc', 'getDoc', 'focus'],
  setup(props, context) {
    let editorView = ref(null)
    const codemirror = ref(null)
    let startState
    const getDoc = () => {
      return editorView.value.state.doc.toString()
    }
    const setDoc = (str) => {
      const cm = editorView.value
      cm?.dispatch({
        changes: { from: 0, to: cm.state.doc.length, insert: str }
      })
    }

    const createEditor = (editorContainer) => {
      if (editorView.value != null) {
        editorView.value.destroy()
      }
      startState = EditorState.create({
        //doc为编辑器内容
        doc: props.doc,
        extensions: [basicSetup, sql({ dialect: MySQL })]
      })

      editorView.value = new EditorView({
        state: startState,
        parent: editorContainer
      })
      if (props.focusInit) {
        editorView.value.focus()
      }
    }
    const focus = () => {
      editorView.value.focus()
    }
    watch(
      () => props.doc,
      (val, preVal) => {
        setDoc(props.doc)
      }
    )
    return {
      codemirror,
      focus,
      getDoc,
      setDoc,
      createEditor
    }
  },
  mounted() {
    const editorContainer = this.codemirror
    this.createEditor(editorContainer)
  }
}
</script>
